﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using CoTime.Model;
using CoTime.Plugins;
using CoTime.View;
using CoTime.ViewModel;

namespace CoTime
{
    public partial class MainWindow : Window
    {
        #region [ Fileds / Properties ]

        #region [ 面板属性 ]

        private WrapPanel CurrentWrapper { get; set; }

        private String CurrentWrapperId
        {
            get
            {
                if (this.CurrentWrapper != null)
                {
                    return this.CurrentWrapper.Name.Replace("UIWrapper", "");
                }
                return String.Empty;
            }
        }

        private WrapPanel NextWrapper
        {
            get { return this.FindName("UIWrapper" + NextWrapperId) as WrapPanel; }
        }

        private Int32 NextWrapperId
        {
            get
            {
                const int maxWapperId = 2;
                var nextWapperId = Convert.ToInt32(CurrentWrapper.Name.Replace("UIWrapper", "")) + 1;
                return (nextWapperId > maxWapperId) ? 1 : nextWapperId;
            }
        }

        private WrapPanel PrevWrapper
        {
            get { return this.FindName("UIWrapper" + PrevWrapperId) as WrapPanel; }
        }

        private Int32 PrevWrapperId
        {
            get
            {
                const int maxWapperId = 2;
                var nextWapperId = Convert.ToInt32(CurrentWrapper.Name.Replace("UIWrapper", "")) - 1;
                return (nextWapperId < 1) ? maxWapperId : nextWapperId;
            }
        }

        private Boolean _wrapper1DataIsToday = true;

        #endregion

        private readonly BackgroundWorker _worker = new BackgroundWorker();

        /// <summary>
        /// 计时器
        /// </summary>
        public PomoTimer PomoTimer { get; set; }

        public UCTdt ucTdt;
        public UCAi ucAi;

        #endregion

        #region [ Window ]

        public MainWindow()
        {
            InitializeComponent();
            SetWindowTitle();

            String taskFile = DateTime.Today.GetTaskFile();
            var viewModel = new MainWindowViewModel(taskFile);

            this.DataContext = viewModel;

            _worker.DoWork += new DoWorkEventHandler(WorkerDoWork);
            _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerRunWorkerCompleted);
            _worker.RunWorkerAsync();

            LoadPlugins();
        }

        private void SetWindowTitle()
        {
            Int32 blankSpace = this.CurrentWrapperId.Equals("2") ? 70 : 30;
            this.Title = String.Format("CoTime 番茄工作法{0} {1} {2}",
                                       new String(' ', blankSpace),
                                       Environment.UserName,
                                       DateTime.Today.ToString("yyyy-MM-dd"));
        }

        private void WindowSizeChanged(object sender, SizeChangedEventArgs e)
        {
            SetWindowTitle();
        }

        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            InitWrapper1UI();
            InitWrapper2UI();
        }

        private void InitWrapper1UI()
        {
            this.ucTdt = new UCTdt(this.DataContext as MainWindowViewModel);
            this.UIWrapper1.Children.Add(ucTdt);

            this.CurrentWrapper = UIWrapper1;
        }

        private void InitWrapper2UI()
        {
            this.ucAi = new UCAi(this.DataContext as MainWindowViewModel);
            this.UIWrapper2.Children.Add(ucAi);
        }

        //TODO:想个好的方法名
        //这个地方的作用是 ToDoToday中浏览以前的历史记录时
        //要把工具栏中的button给冻结掉
        public void AdjustButtonsStatus(Boolean isToday)
        {
            _wrapper1DataIsToday =
                Btn_Timer.IsEnabled =
                Btn_Clear.IsEnabled =
                Btn_Save.IsEnabled =
                Btn_Sync.IsEnabled =
                Btn_Esti.IsEnabled =
                Btn_Pomo.IsEnabled =
                Btn_Aban.IsEnabled =
                Btn_Inte.IsEnabled =
                Btn_Exte.IsEnabled =
                Btn_Done.IsEnabled =
                Btn_Up.IsEnabled =
                Btn_Down.IsEnabled =
                Btn_Sort.IsEnabled =
                Btn_Prev.IsEnabled =
                Btn_Next.IsEnabled =
                isToday;
        }

        private void WindowClosing(object sender, CancelEventArgs e)
        {
            if (this.PomoTimer != null && !this.PomoTimer.IsTimeOver)
            {
                MessageBoxResult result = MessageBox.Show("当前有一个番茄钟在运行，当真要关闭？", "Close CoTime?",
                                                          MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    this.PomoTimer.Close();
                    this.PomoTimer = null;
                    this.ucTdt.WorkingTask.AddAban();
                }
                else if (result == MessageBoxResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
            this.Save();
        }

        #endregion

        #region [ Worker Snyc Service ]

        private void WorkerDoWork(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(TimeSpan.FromSeconds(300));
            Save();
        }

        private void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _worker.RunWorkerAsync();
        }

        public void Save()
        {
            if (!_wrapper1DataIsToday) return;

            List<Task> tasks = this.ucTdt.TasksMapper();
            List<Note> notes = this.ucAi.NotesMapper();

            this.Dispatcher.Invoke(new Action(() =>
                                                  {
                                                      var viewModel = this.DataContext as MainWindowViewModel;
                                                      if (viewModel != null)
                                                      {
                                                          viewModel.Tasks = tasks;
                                                          viewModel.Notes = notes;
                                                          viewModel.Save();
                                                      }
                                                  }));
        }

        #endregion

        #region [ Smart UI ]

        private void FreezePomoBtns()
        {
            //限制pomo相关button
            if (this.ucTdt.SelectedTaskId.Equals(this.ucTdt.WorkingTaskId))
            {
                Btn_Pomo.IsEnabled = false;
                Btn_Aban.IsEnabled = false;
            }
            else
            {
                Btn_Pomo.IsEnabled = true;
                Btn_Aban.IsEnabled = true;
            }
        }

        private void ResizeWindow()
        {
            switch (this.CurrentWrapperId)
            {
                case "1":
                    this.Width = Config.UIWrapper1Size.Width;
                    this.Height = Config.UIWrapper1Size.Height;
                    this.Btn_Clear.Visibility = Visibility.Collapsed;
                    break;
                case "2":
                    InitAcitivityInventoryWapper();
                    this.Btn_Clear.Visibility = Visibility.Visible;
                    break;
            }
        }

        private void InitAcitivityInventoryWapper()
        {
            if (this.ucAi.Background == null)
            {
                this.ucAi.SetUIBackground();
            }
            this.Width = this.ucAi.Width;
            this.Height = this.ucAi.Height + 48;
        }

        private void FreezeToolBar()
        {
            var btns = new Button[]
                           {
                               this.Btn_Pomo,
                               this.Btn_Aban,
                               this.Btn_Inte,
                               this.Btn_Inte,
                               this.Btn_Exte,
                               this.Btn_Done
                           };
            if (this.CurrentWrapper == UIWrapper2)
            {
                this.Btn_Clear.IsEnabled = true;
                foreach (Button btn in btns)
                {
                    btn.IsEnabled = false;
                }
            }
            else
            {
                this.Btn_Clear.IsEnabled = false;
                foreach (Button btn in btns)
                {
                    btn.IsEnabled = true;
                }
            }
        }

        #endregion

        #region [ Button Click ]

        private void ButtonTimerClick(object sender, RoutedEventArgs e)
        {
            if (this.PomoTimer == null || this.PomoTimer.IsTimeOver)
            {
                var pomoTimer = new PomoTimer();
                Double x = SystemParameters.WorkArea.Right - pomoTimer.Width;
                Double y = SystemParameters.WorkArea.Bottom - pomoTimer.Height;
                pomoTimer.Left = x;
                pomoTimer.Top = y;
                pomoTimer.MessageOk = () =>
                                          {
                                              this.ucTdt.FiniPomoOnWorkingTask();
                                              FreezePomoBtns();
                                          };
                pomoTimer.MessageCancel = () =>
                                              {
                                                  this.ucTdt.AbanPomoOnWorkingTask();
                                                  FreezePomoBtns();
                                              };
                pomoTimer.Show();

                this.ucTdt.StartPomoOnWorkingTask();
                this.PomoTimer = pomoTimer;
                this.WindowState = WindowState.Minimized;
            }
            else
            {
                this.PomoTimer.Close();
                this.PomoTimer = null;
                this.ucTdt.AbanPomoOnWorkingTask();
            }
            FreezePomoBtns();
        }

        private void ButtonClearClick(object sender, RoutedEventArgs e)
        {
            if (this.CurrentWrapperId.Equals("2"))
            {
                this.ucAi.ClearDone();
            }
        }

        private void ButtonSaveClick(object sender, RoutedEventArgs e)
        {
            Save();
        }

        private void ButtonSyncClick(object sender, RoutedEventArgs e)
        {
        }

        private void ButtonEstiClick(object sender, RoutedEventArgs e)
        {
            this.ucTdt.SelectedTask.AddEsti();
        }

        private void ButtonPomoClick(object sender, RoutedEventArgs e)
        {
            this.ucTdt.SelectedTask.AddPomo();
        }

        private void ButtonAbanClick(object sender, RoutedEventArgs e)
        {
            this.ucTdt.SelectedTask.AddAban();
        }

        private void ButtonInteClick(object sender, RoutedEventArgs e)
        {
            this.ucTdt.SelectedTask.AddInte();
        }

        private void ButtonExteClick(object sender, RoutedEventArgs e)
        {
            this.ucTdt.SelectedTask.AddExte();
        }

        private void ButtonDoneClick(object sender, RoutedEventArgs e)
        {
            this.ucTdt.SelectedTask.Done();
            SyncBackToNote(this.ucTdt.SelectedTask.Tag as Task);
        }

        private void ButtonUpClick(object sender, RoutedEventArgs e)
        {
        }

        private void ButtonDownClick(object sender, RoutedEventArgs e)
        {
        }

        private void ButtonSortClick(object sender, RoutedEventArgs e)
        {
        }

        private void ButtonPrevClick(object sender, RoutedEventArgs e)
        {
            this.CurrentWrapper.Visibility = Visibility.Collapsed;
            this.PrevWrapper.Visibility = Visibility.Visible;
            this.CurrentWrapper = this.PrevWrapper;
            FreezeToolBar();
            ResizeWindow();
        }

        private void ButtonNextClick(object sender, RoutedEventArgs e)
        {
            this.CurrentWrapper.Visibility = Visibility.Collapsed;
            this.NextWrapper.Visibility = Visibility.Visible;
            this.CurrentWrapper = this.NextWrapper;
            FreezeToolBar();
            ResizeWindow();
        }

        private void ButtonSettingClick(object sender, RoutedEventArgs e)
        {
        }

        #endregion

        #region [ UI Api ]

        public void AddTask(Task task)
        {
            if (!this.CurrentWrapper.Equals(this.UIWrapper1))
                ButtonPrevClick(null, null);
            this.ucTdt.AddTask(task);
        }

        public void SyncBackToNote(Task task)
        {
            this.ucAi.SyncBackToNote(task);
        }

        #endregion

        #region [ Plugins ]

        private void LoadPlugins()
        {
            List<Plugin> plugins = PluginLoader.GetPlugins();
            if (plugins.Count > 0)
            {
                foreach (var plugin in plugins)
                {
                    var toolTip = new ToolTip
                                      {
                                          HorizontalOffset = 10,
                                          VerticalOffset = 5,
                                          Background = Brushes.LightBlue,
                                          Foreground = Brushes.Gray,
                                          FontSize = 14,
                                          Content = plugin.Description
                                      };

                    var button = new Button {ToolTip = toolTip};
                    button.Width = button.Height = 24;

                    //TODO:阴影~~~
                    var imageBrush = new ImageBrush();
                    var bitmap = new BitmapImage(new Uri(plugin.IconPath));
                    {
                        imageBrush.ImageSource = bitmap;
                        imageBrush.Stretch = Stretch.UniformToFill;
                        imageBrush.AlignmentX = AlignmentX.Left;
                        imageBrush.AlignmentY = AlignmentY.Top;
                        button.Background = imageBrush;
                    }
                    ToolBarButtons.Items.Add(button);
                    button.Click += new RoutedEventHandler((object sender, RoutedEventArgs e) => System.Diagnostics.Process.Start(plugin.ExePath));
                }
            }
            #endregion
        }
    }
}